﻿
/*********************************************************************************
--时间：2011-09-19 22:26:26
--作者：jjpeng
--邮箱：ling121211@gmail.com
--说明：XML帮助类
--
*********************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;

using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace PCC.Framework.Utils
{
    public class XmlHelper
    {
        /// <summary>
        /// 将对象序列化为 XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GetXML<T>(T model)
        {          
            return GetXML<T>(model,new Type[]{typeof(T)});
        }

        /// <summary>
        /// 将对象序列化为 XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static string GetXML<T>(T model, params Type[] types)
        {
            XmlSerializer serializeObj = new XmlSerializer(model.GetType(), new Type[] { typeof(T) });
            MemoryStream mstream = new MemoryStream();
            serializeObj.Serialize(mstream, model);
            return Encoding.UTF8.GetString(mstream.ToArray()).Trim();
        }

        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T GetModel<T>(string xmlString)
        {
            return GetModel<T>(xmlString, new Type[] { typeof(T) });
        }

        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static T GetModel<T>(string xmlString, params Type[] types)
        {
            T model = default(T);
            XmlSerializer serializeObj = new XmlSerializer(typeof(T), types);
            MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
            model = (T)serializeObj.Deserialize(mstream);
            return model;
        }

    }
}
